package com.example.aidlclientdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.aidlservicedemo.Person;

public class MessengerActivity extends AppCompatActivity {

    /**
     * 客户端的Messenger
     */
    final Messenger clientMessenger = new Messenger(new IncomingHandler());

    /**
     * 服务端的Messenger
     */
    Messenger serviceMessenger = null;

    boolean isBound;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("JinFu",
                "onServiceConnected() called with: name = [" + name + "], service = [" + service +
                    "]");
            serviceMessenger = new Messenger(service);
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("JinFu", "onServiceDisconnected() called with: name = [" + name + "]");
            serviceMessenger = null;
            isBound = false;
        }
    };

    public static void start(Context context) {
        Intent starter = new Intent(context, MessengerActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messenger);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(v -> {
            if (isBound) {
                Message msg = Message.obtain(null, 1);
                Bundle bundle = new Bundle();
                bundle.putParcelable("person", new Person("小伟", 33));
                msg.setData(bundle);
                msg.replyTo = clientMessenger;
                try {
                    serviceMessenger.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 绑定服务
        Intent intent = new Intent();
        intent.setAction("service.messenger");
        intent.setPackage("com.example.aidlservicedemo");
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
    }

    class IncomingHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    // 处理来自服务端的回复
                    Toast.makeText(MessengerActivity.this, "Received from service: " + msg.obj,
                        Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }

    }

}